<template>
<div class="article-container">
    <!-- 导航栏 -->
    <van-nav-bar class="page-nav-bar" left-arrow title="黑马头条" @click-left="$router.back()"></van-nav-bar>
    <!-- /导航栏 -->

    <div class="main-wrap">
        <!-- 加载中 -->
        <div class="loading-wrap" v-if="isloding">
            <van-loading color="#3296fa" vertical>加载中</van-loading>
        </div>
        <!-- /加载中 -->

        <!-- 加载完成-文章详情 -->
        <div class="article-detail" v-else-if="article.title">
            <!-- 文章标题 -->
            <h1 class="article-title">{{article.title}}</h1>
            <!-- /文章标题 -->

            <!-- 用户信息 -->
            <van-cell class="user-info" center :border="false">
                <van-image class="avatar" slot="icon" round fit="cover" :src="article.aut_photo" />
                <div slot="title" class="user-name">{{article.aut_name}}</div>
                <div slot="label" class="publish-date">{{article.pubdate | relativeTime}}</div>
                <van-button class="follow-btn" type="default" round size="small" icon="plus" v-if="article.is_followed" @click="onFollow" :loading="isLoading">已关注</van-button>
                <van-button v-else class="follow-btn" type="info" color="#3296fa" round size="small" icon="plus" :loading="isLoading" @click="onFollow">关注</van-button>

                <!-- <follow-user :isFollowed="article.is_followed" @update:isFollowed="article.is_followed=$event"  :aut_id="article.aut_id" ></follow-user> -->

                <follow-user :isFollowed.sync="article.is_followed" :aut_id="article.aut_id"></follow-user>

                <!-- <van-button
            class="follow-btn"
            round
            size="small"
          >已关注</van-button> -->
            </van-cell>
            <!-- /用户信息 -->

            <!-- 文章内容 -->
            <div class="article-content markdown-body" v-html="article.content" ref="abc"></div>
            <van-divider>正文结束</van-divider>
            <comment-list :source="article.art_id" @comments-event="total=$event.total_count" :comments="comments" @reply-click="onReply"></comment-list>
            <!-- 底部区域 -->
            <div class="article-bottom">
                <van-button class="comment-btn" type="default" round size="small" @click="isCommentShow=true">写评论</van-button>
                <van-icon name="comment-o" :badge="total" color="#777" />
                <!-- <collect-article :value="article.is_collected" :art_id="article.art_id" @input="article.is_collected=$event"></collect-article> -->
                <collect-article v-model="article.is_collected" :art_id="article.art_id"></collect-article>

                <like-article v-model="article.attitude" :art_id="article.art_id"></like-article>
                <van-icon name="share" color="#777777"></van-icon>
            </div>

            <van-popup v-model="isCommentShow" position="bottom">
                <comment-post :target="article.art_id" @update-post="onUpdatePost"></comment-post>
            </van-popup>

            <!-- /底部区域 -->
        </div>

        <!-- /加载完成-文章详情 -->

        <!-- 加载失败：404 -->
        <div class="error-wrap" v-else-if="isError">
            <van-icon name="failure" />
            <p class="text">该资源不存在或已删除！</p>
        </div>
        <!-- /加载失败：404 -->

        <!-- 加载失败：其它未知错误（例如网络原因或服务端异常） -->
        <div class="error-wrap" v-else>
            <van-icon name="failure" />
            <p class="text">内容加载失败！</p>
            <van-button class="retry-btn">点击重试</van-button>
        </div>
        <!-- /加载失败：其它未知错误（例如网络原因或服务端异常） -->
    </div>

    <van-popup v-model="isReplayShow" position="bottom" :style="{ height: '100%' }">
        <comment-reply v-if="isReplayShow" :comment="comment" @close="isReplayShow=false"></comment-reply>
    </van-popup>
</div>
</template>

<script>
import { getArticleById } from '@/api/article'
import 'github-markdown-css'
import { ImagePreview } from 'vant'
import { addFollow, deleteFollow } from '@/api/user'
import FollowUser from '@/components/follow-user'
import CollectArticle from '@/components/collect-article'
import LikeArticle from '@/components/like-article'
import CommentList from './components/comment-list'
import CommentPost from './components/comment-post'
import CommentReply from './components/comment-reply'

export default {
  name: 'ArticleIndex',
  components: {
    FollowUser,
    CollectArticle,
    LikeArticle,
    CommentList,
    CommentPost,
    CommentReply
  },
  provide: function () {
    return {
      art_id: this.articleId
    }
  },
  props: {
    articleId: {
      type: [Number, String, Object],
      required: true
    }
  },
  data () {
    return {
      article: {},
      isloding: true, // 网络数据还没有请求成功之前，显示loding加载中效果
      isError: false, // 如果这个值是true，说明当前资源找不到 404
      isLoading: false,
      total: 0, // 默认评论的数量
      isCommentShow: false,
      comments: [],
      isReplayShow: false,
      comment: {}
    }
  },
  computed: {},
  watch: {},
  created () {
    this.getList()
  },
  mounted () {},
  methods: {
    async getList () {
      try { // 成功
        const { data:res } = await getArticleById(this.articleId) // eslint-disable-line
        this.article = res.data
        this.isloding = false// 数据加载完成了，就隐藏loding效果
        this.$nextTick(() => {
        // 获取到当前这个东西里面所有的图片，然后收集到一个数组当中，用图片预览初始化一下就可以
          // console.log(this.$refs.abc)
          // 如果只有一个地方用DOM操作，就直接如下的写法
          // 如果多个地方都在做同一样的DOM操作，这个时候推荐封装一个自定义指令封装一下
          var container = this.$refs.abc// 得到文章DOM结构
          var imgList = container.querySelectorAll('img')// 得到当前文章中所有的图片
          var imgs = []// 用来收集所有图片的路径 因为preview插件参数要用这个东西
          imgList.forEach((item, index) => { // 对每个图片DOM进行遍历，把每个人身上的src获取到push到imgs数组中 顺便给每个图片DOM绑定点击事件 点击的时候就初始化图片预览插件
            // console.log(item.src)
            // console.log(index)
            imgs.push(item.src)
            item.onclick = function () {
              ImagePreview({
                startPosition: index,
                images: imgs,
                closeable: true
              })
            }
          })
        })
      } catch (err) {
        if (err.response.status === 404) {
          this.isError = true
        }
        this.isloding = false// 数据加载完成了，就隐藏loding效果
      }
    },
    async onFollow () {
      this.isLoading = true // 开启loading效果
      if (this.article.is_followed === true) { // 说明当前是已关注，我们要做的事情是取消关注
        try {
          await deleteFollow(this.article.aut_id)
        } catch (err) {
          this.article.is_followed = false
        }
      } else if (this.article.is_followed === false) { // 当前是未关注，我们要做的事情是关注
        try {
          await addFollow(this.article.aut_id)
          this.article.is_followed = true
        } catch (err) {
          console.log(err)
          if (err.response.status === 400) {
            this.$toast.fail('自己不能关注自己')
            return
          }
          this.$toast.fail('关注失败')
        }
      }

      this.isLoading = false // 关闭loading效果
    },
    onUpdatePost (item) {
      this.isCommentShow = false
      this.comments.unshift(item)
    },
    onReply (comment) {
      console.log(comment)
      this.comment = comment
      this.isReplayShow = true // 显示弹出层
    }
  }
}
</script>

<style lang="less" scoped>
// npm i github-markdown-css
// 这个东西在node_modules里面，用样式的@import我们的postcss就直接忽略掉，不处理
// @import "~github-markdown-css";
.article-container {
    .main-wrap {
        position: fixed;
        left: 0;
        right: 0;
        top: 92px;
        bottom: 88px;
        overflow-y: scroll;
        background-color: #fff;
    }

    .article-detail {
        .article-title {
            font-size: 40px;
            padding: 50px 32px;
            margin: 0;
            color: #3a3a3a;
        }

        .user-info {
            padding: 0 32px;

            .avatar {
                width: 70px;
                height: 70px;
                margin-right: 17px;
            }

            .van-cell__label {
                margin-top: 0;
            }

            .user-name {
                font-size: 24px;
                color: #3a3a3a;
            }

            .publish-date {
                font-size: 23px;
                color: #b7b7b7;
            }

            .follow-btn {
                width: 170px;
                height: 58px;
            }
        }

        .article-content {
            padding: 55px 32px;

            /deep/ p {
                text-align: justify;
            }
        }
    }

    .loading-wrap {
        padding: 200px 32px;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #fff;
    }

    .error-wrap {
        padding: 200px 32px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        background-color: #fff;

        .van-icon {
            font-size: 122px;
            color: #b4b4b4;
        }

        .text {
            font-size: 30px;
            color: #666666;
            margin: 33px 0 46px;
        }

        .retry-btn {
            width: 280px;
            height: 70px;
            line-height: 70px;
            border: 1px solid #c3c3c3;
            font-size: 30px;
            color: #666666;
        }
    }

    .article-bottom {
        position: fixed;
        left: 0;
        right: 0;
        bottom: 0;
        display: flex;
        justify-content: space-around;
        align-items: center;
        box-sizing: border-box;
        height: 88px;
        border-top: 1px solid #d8d8d8;
        background-color: #fff;

        .comment-btn {
            width: 282px;
            height: 46px;
            border: 2px solid #eeeeee;
            font-size: 30px;
            line-height: 46px;
            color: #a7a7a7;
        }

        .van-icon {
            font-size: 40px;

            .van-info {
                font-size: 16px;
                background-color: #e22829;
            }
        }
    }
}
</style>
